package com.lwm.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 获取单例bean的工厂
 *
 * @author liweimin
 * @date 2021/6/2 16:45
 * @since
 */
public class SingletonBeanFactory {

    /**
     * 定义一个properties对象
     **/
    private static Properties properties;

    /**
     * 容器--->存放bean，保证单例
     **/
    private static Map<String, Object> beanMap;

    //使用静态代码块初始化
    static {
        //注意properties文件基于hashTable 不保证进出顺序
        properties = new Properties();
        InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            properties.load(is);
            //实例化容器
            beanMap = new HashMap<>();

            //遍历properties，实例化对象
            Set<Map.Entry<Object, Object>> entrySet = properties.entrySet();
            for (Map.Entry<Object, Object> entry : entrySet) {
                String beanName = entry.getKey().toString();
                String beanPath = entry.getValue().toString();
                //newInstance 方法如果先加载Service 这哥们去找DAO就找不到 所以要先加载DAO（很蠢的解决方案）
                Object instance = Class.forName(beanPath).newInstance();
                beanMap.put(beanName, instance);
            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("初始化bean.properties异常");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取bean根据Bean名称
     *
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return beanMap.get(beanName);
    }

}
